package com.atguigu.tingshu.album.receiver;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static org.springframework.amqp.rabbit.annotation.Exchange.TRUE;

/**
 * Package: com.atguigu.tingshu.album.receiver
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/23 18:50
 */
@Component
@Slf4j
public class AlbumReceiver {

    private final TrackInfoService trackInfoService;

    public AlbumReceiver(TrackInfoService trackInfoService) {
        this.trackInfoService = trackInfoService;
    }


    /**
     * 监听声音统计信息更新消息
     *
     * @param trackStatMqVo 声音统计信息
     * @param message 消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = TRUE),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {
        Assert.notNull(trackStatMqVo, "声音统计信息不能为空");
        log.info("[专辑服务]监听声音统计信息更新消息，声音id：{}", trackStatMqVo.getTrackId());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            this.trackInfoService.updateTrackStat(trackStatMqVo);
            channel.basicAck(deliveryTag, false);
            log.info("[专辑服务]更新声音统计信息成功，声音id：{}", trackStatMqVo.getTrackId());
        } catch (IOException e) {
            log.error("[专辑服务]更新声音统计信息失败，声音id：{}", trackStatMqVo.getTrackId());
            channel.basicNack(deliveryTag, false, true);
        }

    }
}